package com.yangkunhong.dao;

import com.yangkunhong.utils.DBUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import javax.sql.DataSource;
import java.math.BigInteger;
import java.sql.SQLException;

/*
* DAO是数据访问对象，跟数据库交互的操作
* BaseDao是基类，把公共代码放在基类
* */
public class BaseDao {
    //参数1 SQL语句 含占位符
    //参数2 可变参数
    //
    public static boolean  insert(String insertSQL, Object... params){
        DataSource dataSource = DBUtils.getDataSource();
        //传参目的：操作结束后，自动关闭连接
        //数据库连接池不会正真的关闭连接，而是把连接归还连接池
        QueryRunner queryRunner = new QueryRunner(dataSource);

        Boolean insert = false;
        try {
            insert = queryRunner.insert(insertSQL, resultSet -> {
                if (resultSet.next()) {
                    return true;
                } else {
                    return false;
                }
            }, params);
        } catch (SQLException troubles) {
            System.out.println("插入失败");
            troubles.printStackTrace();
        }
        return insert;

    }
    public static BigInteger getLastInsertId(){
        DataSource dataSource = DBUtils.getDataSource();
        //传参目的：操作结束后，自动关闭连接
        //数据库连接池不会正真的关闭连接，而是把连接归还连接池
        QueryRunner queryRunner = new QueryRunner(dataSource);
        BigInteger id  = BigInteger.valueOf(0);
        try {
            id = queryRunner.query("SELECT LAST_INSERT_ID()", new ScalarHandler<BigInteger>() {
            });
        } catch (SQLException throwables) {
            System.out.println("获取自增ID失败");
            throwables.printStackTrace();
        }
        return id;

    }
}
